package pri.damai.xiaowu.common.log.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import pri.damai.xiaowu.common.log.FilterProperties;
import pri.damai.xiaowu.common.log.trace.WebTraceFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import pri.damai.xiaowu.common.log.trace.feign.FeignTraceInterceptor;

import java.util.Collections;

/**
 * 配置链路追踪的过滤器
 * @Desc Http 请求来时，如果未携带 TraceId ，则为其添加 TraceId
 * @Author DaMai
 * @Date 2021/5/19 16:12
 * 但行好事，莫问前程。
 */
@Slf4j
@Configuration
@ConditionalOnProperty(name = "xiaowu.filter.trace-enable", havingValue = "true")
public class TraceFilterConfig {

    @Bean
    @ConditionalOnMissingBean
    public FilterProperties filterProperties() {
        return new FilterProperties();
    }

    @Bean
    public FilterRegistrationBean<WebTraceFilter> webTraceFilter() {
        FilterRegistrationBean<WebTraceFilter> filter = new FilterRegistrationBean<>();
        filter.setName(WebTraceFilter.FILTER_NAME);
        filter.setFilter(new WebTraceFilter());
        filter.setUrlPatterns(Collections.singletonList(filterProperties().getUrlPattern()));
        log.info("【Xiao Wu】WebTraceFilter 配置成功");

        return filter;
    }

    @Bean
    @ConditionalOnBean(FeignAutoConfiguration.class)
    public FeignTraceInterceptor feignTraceInterceptor() {
        return new FeignTraceInterceptor();
    }

}
